<template>
  <div class="CarsExchangeApply">
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item>车辆管理</el-breadcrumb-item>
      <el-breadcrumb-item><span class="fs14 bold">车辆流转审核</span></el-breadcrumb-item>
    </el-breadcrumb>

    <div class="common-operate-box">
      <el-form class="form-wrap flexMultiWrap" @keyup.enter.native.stop="enterHander">
        <FormWithLabel label="车牌">
          <el-input v-model="tmpData.car" placeholder="车牌"></el-input>
        </FormWithLabel>
        <FormWithLabel label="原训练场">
          <FormInputWithDialog
            :val="inputDiolag.idList"
            v-bind="inputDiolag.innerSelect"
            @update:val="handleInp('id', $event)"/>
        </FormWithLabel>
        <FormWithLabel label="新训练场">
          <FormInputWithDialog
            :val="newInputDiolag.idList"
            v-bind="newInputDiolag.innerSelect"
            @update:val="newHandleInp('id', $event)"/>
        </FormWithLabel>
        <FormWithLabel label="审核状态">
          <el-select v-model="tmpData.status" clearable>
            <el-option label="全部" :value="undefined"></el-option>
            <el-option
              v-for="item in auditStatus" :key="item.value"
              :label="item.text" :value="item.value">
            </el-option>
          </el-select>
        </FormWithLabel>
      </el-form>
      <div class="btn-line flexCenter mt30">
        <button class="btn-operate btn-style-main mr10" @click="search">查询</button>
        <button class="btn-operate btn-style-tan" @click="resert">重置</button>
      </div>
    </div>

    <div class="common-operate-box">
      <el-table :max-height="this.tableMaxHeight()" :data="tableData" border>
        <el-table-column
          type="index" label="序号" width="50"
          header-align="center" align="center">
        </el-table-column>
        <el-table-column
          prop="text" label="状态"
          header-align="center" align="center">
          <template slot-scope="scope">
            <span v-if="scope.row.text==='审核不通过'" class="c-main">{{scope.row.text}}</span>
            <span v-else-if="scope.row.text==='审核通过'" class="c-btn-out">{{scope.row.text}}</span>
            <span v-else>{{scope.row.text}}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="operate" label="操作"
          header-align="center" align="center">
          <template slot-scope="scope">
            <BtnTb
              v-if="scope.row.text==='待审核'" v-auth-id="'CAM030020'"
              @click="handlePreview(scope.row.id)">
              审核
            </BtnTb>
            <BtnTb v-auth-id="'CAM030030'" @click="handleEdit(scope.row.id)" v-else>查看</BtnTb>
          </template>
        </el-table-column>
        <el-table-column
          prop="creator" label="申请人"
          header-align="center" align="center">
        </el-table-column>
        <el-table-column
          prop="createTime" label="申请时间" width="100"
          header-align="center" align="center">
          <template slot-scope="scope">
            {{formatDate(scope.row.createTime, {outType: 'YMD'})}}
          </template>
        </el-table-column>
        <el-table-column
          prop="plateNumber" label="车牌号"
          header-align="center" align="center">
        </el-table-column>
        <el-table-column
          prop="oldSchool" label="原驾校"
          header-align="center" align="center">
        </el-table-column>
        <el-table-column
          prop="oldProject" label="原项目部"
          header-align="center" align="center">
        </el-table-column>
        <el-table-column
          prop="oldDrivingPlace" label="原训练场"
          header-align="center" align="center">
        </el-table-column>
        <el-table-column
          prop="newSchool" label="新驾校"
          header-align="center" align="center">
        </el-table-column>
        <el-table-column
          prop="newProject" label="新项目部"
          header-align="center" align="center">
        </el-table-column>
        <el-table-column
          prop="newDrivingPlace" label="新训练场"
          header-align="center" align="center">
        </el-table-column>
        <el-table-column
          prop="id" label="" v-if="hideRow"
          header-align="center" align="center">
        </el-table-column>
      </el-table>

      <el-pagination
        class="flexCenter mt30"
        background
        :current-page.sync="pageNum" :page-size.sync="pageSize" :total="totalPage"
        :page-sizes="[10, 30, 50, 100]" layout="prev, pager, next, sizes, jumper, total"
        @size-change="ajaxGetData" @current-change="ajaxGetData">
      </el-pagination>
    </div>

    <SelfDialog
      :isShow="isShowDialog" size="l" :titTxt="DialogShowTxt"
      @dialogConfirm="handleConfirm(diologData.id)" @dialogCancel="handleCancel">
      <el-form class="form-wrap flexMultiWrap" :model="diologData">
        <span v-model="diologData.id"></span>
        <FormWithLabel label="车辆">
          <el-input v-model="diologData.plateNumber" placeholder="" :disabled="isdisabled"></el-input>
        </FormWithLabel>

        <div class="fs16 bold" style="width: 100%">车辆信息</div>
        <FormWithLabel label="驾校">
          <el-input v-model="diologData.oldSchool" placeholder="驾校" :disabled="isdisabled"></el-input>
        </FormWithLabel>
        <FormWithLabel label="项目部">
          <el-input v-model="diologData.oldProject" placeholder="项目部" :disabled="isdisabled"></el-input>
        </FormWithLabel>
        <FormWithLabel label="训练场">
          <el-input v-model="diologData.oldDrivingPlace" placeholder="训练场" :disabled="isdisabled"></el-input>
        </FormWithLabel>
        <FormWithLabel label="教练">
          <el-input v-model="diologData.coachName" placeholder="教练" :disabled="isdisabled"></el-input>
        </FormWithLabel>

        <div class="fs16 bold" style="width: 100%">选择新训练场</div>
        <FormWithLabel label="训练场">
          <el-input v-model="diologData.newDrivingPlace" placeholder="训练场" :disabled="isdisabled"></el-input>
        </FormWithLabel>
      </el-form>

      <FormAuditing
        class="mt10"
        :status.sync="status" :readOnly="isreadOnly"
        :txtRes="txtRes"
        :textareaVal.sync="textareaVal" :textareaTit="textareaTit"/>

      <template v-if="isreadOnly === true" slot="bodyAttach">
        <div class="textCenter mt30 mb30"></div>
      </template>
    </SelfDialog>
  </div>
</template>

<script type="text/ecmascript-6">
  import SelfDialog from '@/components/SelfDialog'
  import FormAuditing from '@/components/FormAuditing'
  import FormInputWithDialog from '@/components/FormInputWithDialog'

  import TableEdit from '@/mixins/TableEdit'
  import PagePart from '@/mixins/PagePart'

  export default {
    name: 'CarsExchangeReview',
    components: {SelfDialog, FormAuditing, FormInputWithDialog},
    mixins: [TableEdit, PagePart],
    data () {
      return {
        enterFlag: false,
        tableData: [],
        tmpData: {
          car: '',
          ground: '',
          newGround: '',
          status: this.$route.query.status || undefined
        },
        inputDiolag: {
          scope: '适用部门',
          companysOrPersonals: '', // 文本
          idList: [], // id
          innerSelect: {
            placeholder: '请选择',
            isEditing: false,
            ajaxObj: {
              url: '/api/org/search',
              params: {type: '9'}
            }
          }
        },
        newInputDiolag: {
          scope: '适用部门',
          companysOrPersonals: '', // 文本
          idList: [], // id
          innerSelect: {
            placeholder: '请选择',
            isEditing: false,
            ajaxObj: {
              url: '/api/org/search',
              params: {type: '9'}
            }
          }
        },
        diologData: {},
        auditStatus: [],
        txtRes: ['同意本车辆转场申请', '申请转场审核不通过'],
        status: 'none', //  none ,yes,no
        isreadOnly: false,
        textareaVal: '',
        textareaTit: '请填写退回原因',
        isdisabled: false, // 是否不可编辑
        DialogShowTxt: '', // 弹框标题
        totalPage: 0,
        isShowDialog: false,
        treeSchool: [],
        treeGroup: [],
        treeOldSchoolId: [],
        treeNewSchoolId: [],
        treeOldProjectId: [],
        treeNewProjectId: [],
        hideRow: false
      }
    },
    async mounted () {
      await this.ajaxGetTree()
      this.ajaxGetData()
      this.getStatusInfo()
    },
    methods: {
      enterHander () {
        if (!this.enterFlag) {
          this.ajaxGetData()
          this.enterFlag = true
        }
      },
      ajaxGetData () {
        let postData = {
          ...this.calcPageParams,
          params: {
            plateNumber: this.tmpData['car'], // 车牌号
            oldGroupId: this.inputDiolag.idList, // 训练场
            newGroupId: this.newInputDiolag.idList, // 新训练场Id
            status: this.tmpData['status'] // 审核状态（1待审核，2审核通过，3审核不通过）
          },
          sort: ''
        }
        this.$axios.post('/api/jpCarChangePlace/listCheck', postData)
          .then(res => {
            this.enterFlag = false // 回车功能设为true
            if (res.data.meta.success) {
              this.totalPage = res.data.data.totalSize
              this.tableData = res.data.data.data.map(item => {
                return {
                  ...item,
                  oldDrivingPlace: this.getTxtById('oldGroupId', item.oldGroupId),
                  newDrivingPlace: this.getTxtById('newGroupId', item.newGroupId),
                  oldSchool: this.getTxtById('oldSchoolId', item.oldSchoolId),
                  newSchool: this.getTxtById('newSchoolId', item.newSchoolId),
                  oldProject: this.getTxtById('oldProjectId', item.oldProjectId),
                  newProject: this.getTxtById('newProjectId', item.newProjectId)
                }
              })
            }
          })
      },
      ajaxGetTree () {
        let p1 = this.$axios.post('/api/org/search', {type: '9'})
          .then(res => {
            let resData = res.data.data
            this.treeGroup = [resData] // 树形数据
          })
        let p2 = this.$axios.post('/api/org/search', {type: '9'})
          .then(res => {
            let resData = res.data.data
            this.treeSchool = [resData] // 树形数据
          })
        let oldSchoolId = this.$axios.post('/api/org/search', {type: '7'})
          .then(res => {
            let resData = res.data.data
            this.treeOldSchoolId = [resData] // 树形数据
          })
        let newSchoolId = this.$axios.post('/api/org/search', {type: '7'})
          .then(res => {
            let resData = res.data.data
            this.treeNewSchoolId = [resData] // 树形数据
          })
        let oldProjectId = this.$axios.post('/api/org/search', {type: '8'})
          .then(res => {
            let resData = res.data.data
            this.treeOldProjectId = [resData] // 树形数据
          })
        let newProjectId = this.$axios.post('/api/org/search', {type: '8'})
          .then(res => {
            let resData = res.data.data
            this.treeNewProjectId = [resData] // 树形数据
          })
        return Promise.all([p1, p2, oldSchoolId, newSchoolId, oldProjectId, newProjectId])
      },
      flat (tarData) {
        let key = 'subList'
        if (!tarData[key] || !tarData[key].length) return [tarData]

        let that = this
        let childList = tarData[key].reduce((list, child) => [...list, ...that.flat(child)], [])
        let res = [tarData, ...childList]
        return res
      },
      // 根据ID查找对应文本
      getTxtById (treeListType, id) {
        let treeList = treeListType === 'oldGroupId' ? this.treeSchool : this.treeGroup
        if (treeListType === 'oldGroupId') {
          treeList = this.treeGroup
        } else if (treeListType === 'newGroupId') {
          treeList = this.treeSchool
        } else if (treeListType === 'oldSchoolId') {
          treeList = this.treeOldSchoolId
        } else if (treeListType === 'newSchoolId') {
          treeList = this.treeNewSchoolId
        } else if (treeListType === 'oldProjectId') {
          treeList = this.treeOldProjectId
        } else if (treeListType === 'newProjectId') {
          treeList = this.treeNewProjectId
        }
        let rawFlatData = this.flat(this.deepCopy({subList: treeList}))
        let valText = [id].reduce((sumStr, key) => {
          let find = rawFlatData.find(item => item.id === key)
          if (find) {
            sumStr.push(find['name'])
          }
          return sumStr
        }, [])
        return valText.join(', ')
      },
      search () {
        this.ajaxGetData()
      },
      resert () {
        for (let value in this.tmpData) {
          this.tmpData[value] = ''
        }
        this.inputDiolag['idList'] = []
        this.newInputDiolag['idList'] = []
      },
      // 查看状态
      handleEdit (id) {
        this.DialogShowTxt = '查看车辆流转'
        this.isdisabled = true
        // this.status = 'yes'
        this.isreadOnly = true
        this.$axios.get('/api/jpCarChangePlace/' + id)
          .then(res => {
            if (res.data.meta.success) {
              this.diologData = res.data.data
              if (this.diologData['status'] === 3) {
                this.status = 'yes'
              } else if (this.diologData['status'] === 2) {
                this.status = 'no'
                this.textareaVal = this.diologData['remark']
              }
              this.isShowDialog = true
            }
          })
      },
      // 审核状态
      handlePreview (id) {
        this.DialogShowTxt = '车辆流转审批'
        this.status = 'none'
        this.isreadOnly = false
        this.isdisabled = true
        this.textareaVal = ''
        this.$axios.get('/api/jpCarChangePlace/' + id)
          .then(res => {
            if (res.data.meta.success) {
              this.diologData = res.data.data
            }
            this.isShowDialog = true
          })
      },
      getStatusInfo () {
        this.$axios.get('/api/crmMap/selectByName/jp_car_change_place_status')
          .then(res => {
            if (res.data.meta.success) {
              this.auditStatus = res.data.data
            }
          })
      },
      handleConfirm (id) {
        if (this.status === 'none') {
          this.$message.error('请选择审核结果')
        } else {
          let params = {
            'id': id,
            'remark': this.textareaVal,
            'status': this.status === 'yes' ? '3' : '2'
          }
          this.$axios.post('/api/jpCarChangePlace/update', params)
            .then(res => {
              if (res.data.meta.success) {
                this.isShowDialog = false
                this.$message({
                  message: '提交成功',
                  type: 'success'
                })
                this.ajaxGetData()
              }
            })
        }
      },
      handleInp (type, newVal) {
        this.$set(this.inputDiolag, 'idList', newVal)
      },
      newHandleInp (type, newVal) {
        this.$set(this.newInputDiolag, 'idList', newVal)
      },
      handleCancel () {
        this.isShowDialog = false
      }
    }
  }
</script>

<style scoped rel="stylesheet/scss" type="text/scss" lang="scss">
  .CarsExchangeReview {

  }
</style>
